/* eslint-disable */

import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import axios from 'axios';
import { useEnv } from '@/hooks/useEnv';
import { message } from 'ant-design-vue';
import router from '@/router';

const {
  VITE_MERGER_BASE_URL,
  VITE_SELECTION_BASE_URL,
  VITE_API_PREFIX,
  VITE_PLATFORM_URL,
} = useEnv();

// 创建对齐平台的 axios 实例
const merger_service: AxiosInstance = axios.create({
  baseURL: VITE_MERGER_BASE_URL + VITE_API_PREFIX,
  timeout: 30 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});

merger_service.interceptors.request.use((config: any) => {
  // 这里可以设置token: config!.headers!.Authorization = token
  if (localStorage.getItem('user_token')) {
    config!.headers!.Authorization = localStorage.getItem('user_token');
  }

  return config;
});

merger_service.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data;
    return data;
  },
  err => {
    // 401 token过期 跳转登录页
    console.log(`output->err`, err);
    if (err.response?.status === 401) {
      localStorage.removeItem('user_token');
      message.error('登录已过期，请重新登录');
      setTimeout(() => {
        // window.location.href =
        //   VITE_PLATFORM_URL +
        //   '/login?type=LOGIN&redirect=' +
        //   window.location.href;
        router.push({ path: '/login' });
      }, 1000);
      return;
    }
    if (err.message) {
      message.error(err.message);
    }
    return Promise.reject(err.response);
  }
);

// 创建选型平台的 axios 实例
const selection_service: AxiosInstance = axios.create({
  baseURL: VITE_SELECTION_BASE_URL + VITE_API_PREFIX,
  timeout: 10 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});

selection_service.interceptors.request.use((config: any) => {
  // 这里可以设置token: config!.headers!.Authorization = token
  if (localStorage.getItem('user_token')) {
    config!.headers!.Authorization = localStorage.getItem('user_token');
  }
  return config;
});

selection_service.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data;
    return data;
  },
  err => {
    // 401 token过期 跳转登录页
    console.log(`output->err`, err);
    if (err.response.status === 401) {
      localStorage.removeItem('user_token');
      message.error('登录已过期，请重新登录');
      // setTimeout(() => {
      //   window.location.href =
      //     VITE_PLATFORM_URL +
      //     '/login?type=LOGIN&redirect=' +
      //     window.location.href;
      // }, 1000);
      router.push({ path: '/login' });
      return;
    }
    return Promise.reject(err.response);
  }
);

const http = {
  get<T = any>(url: string, data?: any): Promise<T> {
    return http.request('GET', url, { params: data });
  },
  post<T = any>(url: string, data?: any): Promise<T> {
    return http.request('POST', url, { data });
  },
  put<T = any>(url: string, data?: any): Promise<T> {
    return http.request('PUT', url, { data });
  },
  delete<T = any>(url: string, data?: any): Promise<T> {
    return http.request('DELETE', url, { params: data });
  },
  upload<T = any>(url: string, file: File): Promise<T> {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      merger_service
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data', // 设置 Content-Type
          },
        })
        .then(res => {
          resolve(res as unknown as Promise<T>);
        })
        .catch((e: Error | AxiosError) => {
          reject(e);
        });
    });
  },
  request<T = any>(method = 'GET', url: string, data?: any): Promise<T> {
    return new Promise((resolve, reject) => {
      merger_service({ method, url, ...data })
        .then(res => {
          resolve(res as unknown as Promise<T>);
        })
        .catch((e: Error | AxiosError) => {
          reject(e);
        });
    });
  },
};

const selection_http = {
  get<T = any>(url: string, data?: any): Promise<T> {
    return selection_http.request('GET', url, { params: data });
  },
  post<T = any>(url: string, data?: any): Promise<T> {
    return selection_http.request('POST', url, { data });
  },
  put<T = any>(url: string, data?: any): Promise<T> {
    return selection_http.request('PUT', url, { data });
  },
  delete<T = any>(url: string, data?: any): Promise<T> {
    return selection_http.request('DELETE', url, { params: data });
  },
  upload<T = any>(url: string, file: File): Promise<T> {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      selection_service
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data', // 设置 Content-Type
          },
        })
        .then(res => {
          resolve(res as unknown as Promise<T>);
        })
        .catch((e: Error | AxiosError) => {
          reject(e);
        });
    });
  },
  request<T = any>(method = 'GET', url: string, data?: any): Promise<T> {
    return new Promise((resolve, reject) => {
      selection_service({ method, url, ...data })
        .then(res => {
          resolve(res as unknown as Promise<T>);
        })
        .catch((e: Error | AxiosError) => {
          reject(e);
        });
    });
  },
};

export { selection_http };

export default http;
